<?php
/**
 * Banner 管理
 * @author Mortimer He <mortimerhe@163.com>
 */
namespace Manage\Controller;
use Common\Library\Page;
class BannerController extends CommonController{
	private $msg=array();
	private $Model;
	function _initialize(){
		parent::_initialize();
		$this->Model=D('Banner');
	}
	public function main(){
		$this->redirect('index');
	}

	public function index(){
		if(!$this->checkPermission('Banner')) $this->jump();
		$data=array();
		$count=$this->Model->getCount($data);
		$Page=new Page($count,C('CONFIG_LIMIT_MANAGE'));
		$Page->setConfig('header',L('page_header'));
		$Page->setConfig('theme',L('page_theme'));
		$data['start']=$Page->firstRow;
		$data['limit']=$Page->listRows;
		$list=$this->Model->getBanners($data);
		$show=$Page->show();
		$url['p']=I('get.p','');
		$this->assign('list',$list);
		$this->assign('url',$url);
		$this->assign('page',$show);
		$this->display();
	}

	public function oper($banner_id=0){
		if(!$banner_id && !$this->checkPermission('AddBanner')) $this->jump();
		$languages=get_langs();
		$banner=array();
		if($banner_id) $banner=$this->Model->getBanner($banner_id);
		if($banner_id && empty($banner)) $this->jump(L('error_404'));
		if(IS_POST){
			$banner=I('post.');			
			if($this->vilidateForm()) {
				$this->Model->operBanner($banner,$banner_id);
				session('success',$banner_id?L('success_edit'):L('success_add'));
				$url['p']=I('get.p','');
				$this->redirect('index',$url);
			}else{
				if(!isset($this->msg['warning'])) $this->msg['warning']=L('error_warning');
			}
		}
		foreach ($banner['banner_image'] as $k => $v) {
			$banner['banner_image'][$k]['thumb']=image_resize($v['image'],100,100);
			$banner['banner_image'][$k]['mobile_thumb']=image_resize($v['mobile'],100,100);
		}
		$banner['placeholder']=image_resize();
		$this->assign('languages',$languages);
		$this->assign('banner',$banner);
		$this->assign('msg',$this->msg);
		$this->display();
	}

	private function vilidateForm(){
		$banner_id = I('get.banner_id',0,'trim');
		if($banner_id && !$this->checkPermission('EditBanner')){
			$this->msg['warning']=L('error_not_permission');
			return !$this->msg;
		}
		$data=I('post.');
		if(mb_strlen($data['name'])<2 || mb_strlen($data['name'])>50){
			$this->msg['name']	=	L('error_name');
		}
		return !$this->msg;
	}

	public function del(){
		if($this->checkPermission('DeleteBanner')){
			$banner_ids=I('post.selected');
			$count=0;
			foreach($banner_ids as $banner_id){
				$count += $this->Model->del($banner_id);
			}
			if($count){
				session('success',L('success_delete',array('count'=>$count)));
			}
		}else{
			session('danger',L('error_not_permission'));
		}
		$this->redirect('index');
	}
}